package com.xiaoluyy.demo.common.util;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpsClient {


    private static Logger log = LoggerFactory.getLogger(HttpsClient.class);

    static RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setSocketTimeout(600)
            .setConnectTimeout(600)
            .setConnectionRequestTimeout(600)
            .setStaleConnectionCheckEnabled(true)
            .build();

    public static CloseableHttpClient createHttpClient_AcceptsUntrustedCerts() throws Exception {
        HttpClientBuilder b = HttpClientBuilder.create();

        // setup a Trust Strategy that allows all certificates.
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
        b.setSslcontext( sslContext);

        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();

        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
        b.setConnectionManager( connMgr);

        return b.build();
    }
    public static HttpResult post(String url, String jsonStr, Map<String, String> headers) {
        HttpResult result = null;
        CloseableHttpClient httpClient = null;
        try {
            httpClient = createHttpClient_AcceptsUntrustedCerts();
            log.info("HttpsClient create httppost:" + url);
            HttpPost post = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
            post.setConfig(requestConfig);
            if(headers != null) {
                for (String key : headers.keySet()) {
                    post.addHeader(key, headers.get(key));
                }
            }
            String requestContent = jsonStr;
            if (!StringUtils.isEmpty(requestContent)) {
                HttpEntity entity = new StringEntity(requestContent, ContentType.APPLICATION_JSON);
                post.setEntity(entity);
            }
            result = invoke(httpClient, post);

        } catch (Exception e) {
            log.error("HttpsClient invoke post failed,url:" + url + ",data:" + JSON.toJSONString(jsonStr), e);
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error("HttpsClient close failed,url:" + url + ",data:" + JSON.toJSONString(jsonStr), e);
            }
        }

        return result;
    }

    public static HttpResult get(String url) {
        HttpResult result = null;
        CloseableHttpClient httpClient = null;
        try {
            httpClient = createHttpClient_AcceptsUntrustedCerts();
            log.info("HttpsClient create httpget:" + url);
            HttpGet get = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
            get.setConfig(requestConfig);
            result = invoke(httpClient, get);

        } catch (Exception e) {
            log.error("HttpsClient invoke get failed,url:" + url, e);
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error("HttpsClient close failed,url:" + url, e);
            }
        }

        return result;
    }

    private static HttpResult invoke(org.apache.http.client.HttpClient httpclient,
                                     HttpUriRequest httpost) {

        HttpResponse response = sendRequest(httpclient, httpost);
        HttpResult result = paseResponse(response);

        return result;
    }

    private static HttpResult paseResponse(HttpResponse response) {

        HttpResult result = new HttpResult();
        if (response == null || response.getStatusLine() == null || response.getEntity() == null) {
            result.setStatusCode(500);
            result.setBody("HttpsClient response return null.");
            return result;
        }
        result.setStatusCode(response.getStatusLine().getStatusCode());
        log.info("HttpsClient get response from http server.." + " response code:" + result.getStatusCode());
        HttpEntity entity = response.getEntity();

        log.info("HttpsClient response status: " + response.getStatusLine());
        String charset = EntityUtils.getContentCharSet(entity);
        log.info("HttpsClient response charset:" + charset);

        String body = null;
        try {
            body = EntityUtils.toString(entity, "UTF-8");
            result.setBody(body);
            log.info("HttpsClient paseResponse body:" + body);
        } catch (Exception e) {
            log.error("HttpsClient paseResponse failed due to Exception,", e);
        }
        return result;
    }

    private static HttpResponse sendRequest(org.apache.http.client.HttpClient httpclient,
                                            HttpUriRequest httpost) {
        log.info("HttpsClient execute post...");
        HttpResponse response = null;
        System.setProperty("jsse.enableSNIExtension", "false");
        try {
            response = httpclient.execute(httpost);
        } catch (ClientProtocolException e) {
            log.error("HttpsClient sendRequest failed due to ClientProtocolException,", e);
        } catch (IOException e) {
            log.error("HttpsClient sendRequest failed due to IOException,", e);
        }
        return response;
    }

    private static HttpPost postForm(String url, Map<String, String> params) {

        HttpPost httpost = new HttpPost(url);

        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
        httpost.setConfig(requestConfig);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }

        try {
            log.info("HttpsClient set utf-8 form entity to httppost");
            httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("HttpsClient postForm set encoding failed,", e);
        }

        return httpost;
    }

    public static class HttpResult {
        private Integer statusCode;

        private String body;

        public Integer getStatusCode() {
            return statusCode;
        }

        public void setStatusCode(Integer statusCode) {
            this.statusCode = statusCode;
        }

        public String getBody() {
            return body;
        }

        public void setBody(String body) {
            this.body = body;
        }

    }

}

